package com.example.musicplayer.activity;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.musicplayer.DataLoadManager;
import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.BaseFragmentPagerAdapter;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.fragment.MainTab1Fragment;
import com.example.musicplayer.fragment.MainTab2Fragment;
import com.example.musicplayer.fragment.MainTab3Fragment;
import com.example.musicplayer.fragment.MainTab4Fragment;
import com.example.musicplayer.fragment.dialogFragment.MusicListDialogFragment;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.service.MusicTabViewService;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements MusicListDialogFragment.CallBackListener {
    private List<View> mBottomTabs;
    private List<ImageView> mBottomTabImages;
    private List<TextView> mBottomTabText;
    private ViewPager mViewPagerMain;
    //记录上一次按下back键时间，实现按两次退出
    private long mPreTime;
    //按一次退出键时弹出，提示要按两次才能退出
    private ToastUtil mToastUtil;

    private MusicService.MusicBinder mMusicBinder;
    private final ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMusicBinder = (MusicService.MusicBinder) service;
            if (mMusicBinder != null) {
                registerMusicListener(mMusicBinder);
            }
            checkPlayingState();
            if (MusicPlayerApplication.canDrawOverlays()) {
                Intent intent = new Intent(MainActivity.this, MusicTabViewService.class);
                bindService(intent, mMusicTabViewConnection, BIND_AUTO_CREATE);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMusicBinder = null;
        }
    };

    private MusicTabViewService.MusicTabViewBinder mMusicTabViewBinder;
    private final ServiceConnection mMusicTabViewConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMusicTabViewBinder = (MusicTabViewService.MusicTabViewBinder) service;
            mMusicTabViewBinder.setMusicBinder(mMusicBinder);
            mMusicTabViewBinder.shouldShowView(MusicPlayerApplication.getInstance().isForeground());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMusicTabViewBinder = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WindowTools.lightStatusBar(getWindow());
        if (DataLoadManager.getInstance() != null) {
            DataLoadManager.getInstance().readBaseData();
        }

        initView();
        addListener();
        startService();
        bindMusicService();
        setEnableMusicListener(true);
        //show music playing info tab
        setEnableMusicTabView(true);
        setEnableTimer(true, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //重置上一次点击返回键的时间
        mPreTime = 0;
        checkPlayingState();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mMusicTabViewConnection);
        unbindService(mConnection);
        if (mMusicBinder != null) {
            mMusicBinder.pause();
            mMusicBinder = null;
        }
        stopService(new Intent(this, MusicService.class));
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mMusicBinder != null && hasFocus) {
            registerMusicListener(mMusicBinder);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - mPreTime) > 2000) {
                mToastUtil = new ToastUtil(this, "再次点击返回键切换到桌面")
                        .shortShow()
                        .setGravity(Gravity.BOTTOM, 0, 360)
                        .setAlpha(0.7f)
                        .show();
                mPreTime = currentTime;
            } else {
                onBackPressed();
                if (mToastUtil != null) {
                    mToastUtil.cancel();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //设置应用按返回建再次进入不会出现启动页面，并且需要按两次才能退出
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    //得到组件对象并初始化viewPager
    private void initView() {
        mBottomTabs = new ArrayList<View>();
        mBottomTabs.add(findViewById(R.id.linear_layout_tab1));
        mBottomTabs.add(findViewById(R.id.linear_layout_tab2));
        mBottomTabs.add(findViewById(R.id.linear_layout_tab3));
        mBottomTabs.add(findViewById(R.id.linear_layout_tab4));
        mBottomTabImages = new ArrayList<ImageView>();
        mBottomTabImages.add((ImageView) findViewById(R.id.imageview_tab1));
        mBottomTabImages.add((ImageView) findViewById(R.id.imageview_tab2));
        mBottomTabImages.add((ImageView) findViewById(R.id.imageview_tab3));
        mBottomTabImages.add((ImageView) findViewById(R.id.imageview_tab4));
        mBottomTabText = new ArrayList<TextView>();
        mBottomTabText.add((TextView) findViewById(R.id.textview_tab1));
        mBottomTabText.add((TextView) findViewById(R.id.textview_tab2));
        mBottomTabText.add((TextView) findViewById(R.id.textview_tab3));
        mBottomTabText.add((TextView) findViewById(R.id.textview_tab4));
        mViewPagerMain = findViewById(R.id.viewpager_main);

        List<Fragment> list = new ArrayList<Fragment>();
        list.add(new MainTab1Fragment());
        list.add(new MainTab2Fragment());
        list.add(new MainTab3Fragment());
        list.add(new MainTab4Fragment());
        mViewPagerMain.setAdapter(new BaseFragmentPagerAdapter(getSupportFragmentManager(), 1, list));
        updateBottomTab(mBottomTabs.size() > 0 ? mBottomTabs.get(0) : null);
    }

    //给组件添加监听器
    private void addListener() {
        for (int i = 0; i < mBottomTabs.size(); i++) {
            final View view = mBottomTabs.get(i);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateBottomTab(view);
                }
            });
        }
        mViewPagerMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position < mBottomTabs.size())
                    updateBottomTab(mBottomTabs.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //更新页面底部栏的选择状态
    private void updateBottomTab(View view) {
        int position = mBottomTabs.contains(view) ? mBottomTabs.indexOf(view) : 0;
        mViewPagerMain.setCurrentItem(position);
        for (int i = 0; i < mBottomTabs.size(); i++) {
            if (i < mBottomTabImages.size()) {
                if (i == position)
                    mBottomTabImages.get(i).getDrawable().setTint(getResources().getColor(R.color.spring_green));
                else
                    mBottomTabImages.get(i).getDrawable().setTint(getResources().getColor(R.color.tab_not_selected));
            }
            if (i < mBottomTabText.size()) {
                if (i == position)
                    mBottomTabText.get(i).setTextColor(getResources().getColor(R.color.spring_green));
                else
                    mBottomTabText.get(i).setTextColor(getResources().getColor(R.color.light_gray));
            }
        }
    }

    //当播放状态变化时调用
    private void checkPlayingState() {
        if (mMusicBinder != null) {
            if (mMusicBinder.hasMusic()) {
                startTimer();
            } else {
                pauseTimer();
            }
        }
    }

    //绑定到音乐播放服务
    private void bindMusicService() {
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, mConnection, Service.BIND_AUTO_CREATE);
    }

    //启动音乐后台服务
    private void startService() {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
    }

    @Override
    public MusicService.MusicBinder getBinder() {
        return mMusicBinder;
    }

    @Override
    public void onMusicListShow() {
    }

    @Override
    public void onMusicListDismiss() {
    }

    @Override
    protected boolean onRefreshView() {
        boolean result = super.onRefreshView();
        if (mMusicBinder != null) {
            if (mMusicTabViewBinder != null) {
                mMusicTabViewBinder.refreshView();
            }
            if (!mMusicBinder.isPlaying()) {
                result = false;
            }
        }
        return result;
    }

    @Override
    public void onMusicPrepared(MusicInfo musicInfo) {
        checkPlayingState();
        if (mMusicTabViewBinder != null) {
            mMusicTabViewBinder.updateMusicTab();
        }
    }

    @Override
    public void onMusicEmpty(MusicInfo musicInfo) {
        checkPlayingState();
        if (mMusicTabViewBinder != null) {
            mMusicTabViewBinder.updateMusicTab();
        }
    }

    @Override
    public void onMusicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
        checkPlayingState();
        if (mMusicTabViewBinder != null) {
            mMusicTabViewBinder.updatePlayingState();
        }
    }

    @Override
    protected void onMusicPlayModeChanged(MusicInfo musicInfo, MusicPlayMode mode) {
        if (mMusicTabViewBinder != null) {
            mMusicTabViewBinder.updatePlayModeChanged();
        }
    }

    @Override
    public void jumpToMusicPlayActivity() {
        if (mMusicBinder.getMusicCounts() > 0) {
            pauseTimer();
            super.jumpToMusicPlayActivity();
        }
    }

    //保存音乐播放状态
    public void saveMusicPlayState() {
        if (mMusicBinder != null) {
            mMusicBinder.saveMusicPlayState();
        }
    }

    public Binder tryGetMusicBinder() {
        return mMusicBinder;
    }

    public Binder tryGetMusicTabViewBinder() {
        return mMusicTabViewBinder;
    }

    public Binder tryGetDesktopLyricBinder() {
        return mMusicBinder == null ? null : mMusicBinder.getDesktopLyricBinder();
    }
}